const app = getApp();

Page({
  data: {
    id: '',
    goodsList: [],
    page: 0,
    rows: 20,
    loadingSta: 1,
  },
  onLoad(query) {
    this.setData({
      id: query.param
    })
    my.setNavigationBar({
      reset: true
    });
    this.resetList();
    this.getGoodsList();
  },

  resetList(){
    let data = {
      goodsList: [],
      page: 0,
      rows: 20,
      loadingSta: 1,
    }
    this.setData(data);
  },


  // 加载
  lower(){
    this.getGoodsList();
  },


  getGoodsList(){
    let pages = this.data.page;
    pages += 1;
      
    let dat = {
      sortType: 1,
      sid: this.data.id,
      page: pages,
      rows: this.data.rows
    }

    my.showLoading({
      content: '加载中...',
    });
    this.setData({
      loadingSta: 2,
    })

    app.product.findAllProduct(dat)
    .then(res=>{
      if(res.data && res.data.list.length > 0){
        let newList = this.data.goodsList;
        this.dataPromise(res.data.list)
        .then(dat=>{
          newList.push(...dat);
          this.setData({
            goodsList: newList,
            page: pages,
            loadingSta: 1,
          })
        })

      }else{
        this.setData({
          loadingSta: 3,
        })
      }
      my.hideLoading();
    })
    .catch(err=>{
      my.hideLoading();
    })

  },





  // 转价格
  dataPromise(list) {
      return new Promise((relose, reject) => {
          list.forEach((item) => {
              item.category = JSON.parse(item.category)
              item.colors = JSON.parse(item.colors)
              item.match = JSON.parse(item.match)
              item.params = JSON.parse(item.params)
              item.slideshows = JSON.parse(item.slideshows)
              item.img = item.slideshows[0]
              item.title = item.tit
              this.getminPrice(item.params)
                  .then(res => {
                      item.price = res
                  })
          })
          relose(list)
      })
  },

  getminPrice(params) {
      return new Promise((resole, reject) => {
          let prices = []
          for (let i = 0; i < params.length; i++) {
              for (let t = 0; t < params[i].term_list.length; t++) {
                  for (let s = 0; s < params[i].term_list[t].specifications.length; s++) {
                      let price = (params[i].term_list[t].specifications[s].money / params[i].term_list[t].value / 100).toFixed(2)
                      prices.push(price)
                  }
              }
          }
          let minprice = Math.min.apply(null, prices);
          resole(minprice)
      })
  },


  // 跳转
  navigateTo(e){
    app.navigateTo(e)
  },



});
